<?php

class framework_base_curl {
	public $host;
	public $url;
	public $link;
	public $headers = array ();
	public $params = array ();
	public $cookies = array ();
	public $ssl = false;
	public $debug = false;
	public $info;
	public $result;
	public $method = 'get';
	public $config;
	public $timeout = 30;
	
	
	public function init() {
		$this->params = array ();
		$this->info = array ();
		$this->result = '';
	}
	
	public function exec() {
		$this->link = $this->host . $this->url;
		if($this->params)
	  		$this->link .='?' . http_build_query($this->params);
		$ch = curl_init($this->link);
		curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, strtoupper ( $this->method ) );
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt ( $ch, CURLOPT_TIMEOUT,$this->timeout);//设置默认超时时间为30秒
		if ($this->ssl === true) {
			curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, 1 );
			curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
		}
		if ($this->headers) {
			$headers = array ();
			foreach ( $this->headers as $k => $v )
				$headers [] = $k . ':' . $v;
			curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
		}
		if($this->cookies){
			$cookies='';
			foreach($this->cookies as $k=>$v){
				$cookies.=$k.'='.$v.'; ';
			}
			curl_setopt($ch,CURLOPT_COOKIE,substr($cookies,0,-2));
		}

		$this->result = curl_exec($ch);
		if($this->debug)
		{
			$this->info = curl_getinfo ( $ch );
			var_dump($this->info);
			echo $this->result;
			exit;
		}
		curl_close ( $ch );
	}

	public function output() {
       echo $this->result;
	}
	
	public function outputJson($return=false) {
		$dom = new DOMDocument;
		$response = $this->result;
		$response = preg_replace("/\<\!\[CDATA\[(.*?)\]\]\>/s", "$1", $response);
		@$dom->loadXML($response);
		if (!$dom->documentElement) {
		    exit('{"error":"error"}');
		}
		$xml = new SimpleXMLElement($response);
		if($return)
			return json_encode($xml);
		else
			echo json_encode($xml);
	}

}
